<?php

function EscapeString($str)
{
	return $str;
	//return mysql_escape_string($str);
}

//获取配置文件信息------------------
function GetConfInfo($str)
{
	return $GLOBALS[$str];
}
//获取上传文件路径
function GetUploadPath()
{
	return GetConfInfo("update_path");
}

//获取路径(上传图片路径)
function getUploadPathExt($tmpUID)
{
	$upload_root = '../' . GetConfInfo("update_path");						//上传根目录
	$upload_photp_dir = $upload_root . GetConfInfo("update_path_photo");	//上传相片路径

	$user_zone = intval($tmpUID / 10000);
	$savePath = $user_zone. "/" . $tmpUID . "/";
	$newPath = $upload_photp_dir . $savePath;
	return $newPath;
}

function GetCommandPage()
{
	return $_REQUEST["command_page"];
}
function GetCommandType()
{
	return $_REQUEST["command_type"];
}
function GetRequest($name)
{
	if(isset($_REQUEST[$name])) return $_REQUEST[$name];
	else return "";
}

//获取当前时间
function GetDateTime()
{
	//date_default_timezone_set("UTC");
	return date("Y-m-d H:i:s");
}
//获取来源IP
function GetHostIP()
{
	return $_SERVER["REMOTE_ADDR"];
}


//---------------------------------------------------
//新建目录(path不能包含文件名)
function CreateFolder($path)
{
	if (!file_exists($path))
	{
		CreateFolder(dirname($path));
		mkdir($path, 0777);
	}
}
//删除文件
function DeleteFile($path)
{
	if(!file_exists($path)) return false;
	return unlink($path);//文件存在 则删除
}
//删除文件列表
function DeleteFileArray($fileInfos)
{
	foreach($fileInfos as $info)
	{
		$path = $info["fullpath"];
		DeleteFile($path);//删除
	}
}
//文件是否存在
function isFileExists($oldName)
{
	return file_exists($oldName) ? "true" : "false";
}


//---------------------------------------------------
//文件上传------------------
function UploadFile($fileInputName, $newPath, $newName)
{
	if(!isset($_FILES[$fileInputName]))
		return "";

	$files = $_FILES[$fileInputName];
	$errors = $files["error"];
	$tempName = $files['tmp_name'];

	if($errors == UPLOAD_ERR_OK)
	{
		CreateFolder($newPath);  //目录不存在则新建
		move_uploaded_file($tempName, $newPath . $newName);//保存文件
		return " success :" . $newPath . $newName ;
	}
	return "file not exists... ";
}
//检查文件信息， 如文件后缀
function CheckFileInfo($fileInputName)
{
	if(!isset($_FILES[$fileInputName]))
		return "";

	$files = $_FILES[$fileInputName];
	$errors = $files["error"];
	$name = $files['name'];

	if($errors != UPLOAD_ERR_OK)
	{
		die("文件上传过程出错....". $name);
		return false;
	}

	if(GetFileExtName($name) != GetConfInfo("update_filetype"))
	{
		die("文件后缀名不符..." . $name);
		return false;
	}
	return true;
}
//重命名文件(old, new)
function RenameFile($oldName, $newName)
{
	if(!file_exists($oldName))
        return false;

	rename($oldName, $newName);
	return true;
}

//获取上传文件信息(无使用)
function GetUploadFileInfo($userfileName)
{
	$files = $_FILES[$userfileName];
	$name = $files['name'];
	$extname = GetFileExtName($name);

	return array("name" => $name, "extname" => $extname);
}
//获取文件后缀名(无使用)
function GetFileExtName($fileName)
{
	$tempA = explode(".", $fileName);
	return ($tempA[count($tempA)-1]);
}


//--------------获取文件全路径-----------
//打扮文件信息 
function GetBeautifulFileInfo($type_1, $type_2, $type_3, $id, $sex)
{
	// 路径为 uploadPathRoot/tablename/id_gender_0.swf
	$newPath = GetUploadPath() . GetConfInfo("update_path_" . $type_1);
	$postfix = GetConfInfo("update_filetype");  	//后缀
	if($type_2 == "music")
	{	
		$sex = 0;
		$postfix = "mp3";
	}
	
	$newfilename =  $id . "_" . $sex . "_" ;
	$newfilename_0 = $newfilename . "0." . $postfix;//文件名
	$newfilename_1 = $newfilename . "1." . $postfix;//文件名
	$newfilename_2 = $newfilename . "2." . $postfix;//文件名
	$newfilename_3 = $newfilename . "3." . $postfix;//文件名
	$newfilename_4 = $newfilename . "4." . $postfix;//文件名
	
	$fullpath_0 = $newPath . $newfilename_0; 		//全路径
	$fullpath_1 = $newPath . $newfilename_1;		//全路径
	$fullpath_2 = $newPath . $newfilename_2;		//全路径
	$fullpath_3 = $newPath . $newfilename_3;		//全路径
	$fullpath_4 = $newPath . $newfilename_4;		//全路径

	$infoArray = array();
	$infoArray[] = array("name"=>$newfilename_0, "postfix"=>$postfix, "fullpath"=>$fullpath_0, "path"=>$newPath);
	$infoArray[] = array("name"=>$newfilename_1, "postfix"=>$postfix, "fullpath"=>$fullpath_1, "path"=>$newPath);
	$infoArray[] = array("name"=>$newfilename_2, "postfix"=>$postfix, "fullpath"=>$fullpath_2, "path"=>$newPath);
	$infoArray[] = array("name"=>$newfilename_3, "postfix"=>$postfix, "fullpath"=>$fullpath_3, "path"=>$newPath);
	$infoArray[] = array("name"=>$newfilename_4, "postfix"=>$postfix, "fullpath"=>$fullpath_4, "path"=>$newPath);
	
	return $infoArray;
}
function GetBeautifulPath($type_1)
{
	// 路径为 uploadPathRoot/type_1/
	return GetUploadPath() . GetConfInfo("update_path_" . $type_1);
}

//修改打扮文件的名字(性别改变的时候使用)
function EditBeautifulFileName($type_1, $id, $sex, $NewID, $NewSex)
{
	// 路径为 uploadPathRoot/type_1/id_gender_0.swf
	$newPath = GetUploadPath() . GetConfInfo("update_path_" . $type_1);
	$postfix = GetConfInfo("update_filetype");  	//后缀

	if($type_2 == "music")
	{	
		$sex = 0;
		$NewSex = 0;
		$postfix = "mp3";
	}

	$newfilename =  $id . "_" . $sex;
	$fullpath_0 = $newPath . $newfilename . "_0." . $postfix; 		//全路径
	$fullpath_1 = $newPath . $newfilename . "_1." . $postfix;		//全路径
	$fullpath_2 = $newPath . $newfilename . "_2." . $postfix;		//全路径
	$fullpath_3 = $newPath . $newfilename . "_3." . $postfix;		//全路径
	$fullpath_4 = $newPath . $newfilename . "_4." . $postfix;		//全路径

	$newfilename_new =  $NewID . "_" . $NewSex;
	$fullpath_0_new = $newPath . $newfilename_new . "_0." . $postfix; 	//新全路径
	$fullpath_1_new = $newPath . $newfilename_new . "_1." . $postfix;	//新全路径
	$fullpath_2_new = $newPath . $newfilename_new . "_2." . $postfix;	//新全路径
	$fullpath_3_new = $newPath . $newfilename_new . "_3." . $postfix;	//新全路径
	$fullpath_4_new = $newPath . $newfilename_new . "_4." . $postfix;	//新全路径

	RenameFile($fullpath_0, $fullpath_0_new);	//改名
	RenameFile($fullpath_1, $fullpath_1_new);   //改名
	RenameFile($fullpath_2, $fullpath_2_new);   //改名
	RenameFile($fullpath_3, $fullpath_3_new);   //改名
	RenameFile($fullpath_4, $fullpath_4_new);   //改名
}

//判断文件是否存在
function JudgeFileName($type_1, $type_2, $id, $sex)
{
	// 路径为 uploadPathRoot/type_1/id_gender_0.swf
	$newPath = GetUploadPath() . GetConfInfo("update_path_" . $type_1);
	$postfix = GetConfInfo("update_filetype");  	//后缀
	if($type_2 == "music") 
	{
		$sex = 0; 
		$postfix = "mp3";
	}
	
	$tmpArray = array();	
	
	if($sex == 2) {$sex = 0; }	
	$newfilename =  $id . "_" . $sex;
	$fullpath_0 = $newPath . $newfilename . "_0." . $postfix; 		//全路径
	$fullpath_1 = $newPath . $newfilename . "_1." . $postfix;		//全路径
	$fullpath_2 = $newPath . $newfilename . "_2." . $postfix;		//全路径  
	$fullpath_3 = $newPath . $newfilename . "_3." . $postfix;		//全路径  
	$fullpath_4 = $newPath . $newfilename . "_4." . $postfix;		//全路径  
	
	$tmpArray["file_0"] = isFileExists($fullpath_0);
	$tmpArray["file_1"] = isFileExists($fullpath_1);
	$tmpArray["file_2"] = isFileExists($fullpath_2);
	$tmpArray["file_3"] = isFileExists($fullpath_3);
	$tmpArray["file_4"] = isFileExists($fullpath_4);
	
	if($sex == 2)  #$sex = 2: 男与女
	{
		$sex = 1;
		$newfilename =  $id . "_" . $sex;
		$fullpath_0 = $newPath . $newfilename . "_0." . $postfix; 		//全路径
		$fullpath_1 = $newPath . $newfilename . "_1." . $postfix;		//全路径
		$fullpath_2 = $newPath . $newfilename . "_2." . $postfix;		//全路径  
		$fullpath_3 = $newPath . $newfilename . "_3." . $postfix;		//全路径  
		$fullpath_4 = $newPath . $newfilename . "_4." . $postfix;		//全路径  
		
		$tmpArray["file_0"] |= isFileExists($fullpath_0);
		$tmpArray["file_1"] |= isFileExists($fullpath_1);
		$tmpArray["file_2"] |= isFileExists($fullpath_2);
		$tmpArray["file_3"] |= isFileExists($fullpath_3);
		$tmpArray["file_4"] |= isFileExists($fullpath_4);
	}
	
	return $tmpArray;
}


//---------------------------------------------------
//字符转换------------------
function GB2UTF8($str)
{
	return iconv("utf-8", "gb2312", $str);
}
function UTF82GB($str)
{
	return iconv("gb2312", "utf-8", $str);
}


//---------------------------------------------------
//返回json格式的字符串给web
function ReturnJSON($result, $msg="", $error="", $success = "true")
{
	$iRowLen = mysql_num_rows($result);
	if($success == true) $success = "true";
	if($success == false) $success = "false";

	$str = "{\n";
	$str =  $str ."\"dataset\":\n[";
	while($row = mysql_fetch_assoc($result))
	{
		$str =  $str . "\n\t";
		$str =  $str . json_encode2($row);

		$iRowLen--;
		if($iRowLen > 0)
			 $str =  $str . ",";

	}
	$str =  $str ."\n],\n";
	$str =  $str ."\"success\":" . $success ."," ;
	$str =  $str . "\n";
	$str =  $str ."\"error\": \"" . ProveJSONStr($error) . "\"," ;
	$str =  $str . "\n";
	$str =  $str ."\"message\": \"" . $msg . "\"" ;
	$str =  $str . "\n";
	$str =  $str ."}";
	echo $str;
}
//返回查询结果集数组json给web
function ReturnJSONFromResultArray($array, $error="", $msg="", $success = "true")
{
	if($success == true) $success = "true";
	if($success == false) $success = "false";

	$str = "{\n";
	$str =  $str ."\"dataset\":\n";

	$str =  $str . "\n\t";
	$str =  $str . json_encode2($array);

	$str =  $str ."\n,\n";
	$str =  $str ."\"success\":" . $success ."," ;
	$str =  $str . "\n";
	$str =  $str ."\"error\": \"" . ProveJSONStr($error) . "\"," ;
	$str =  $str . "\n";
	$str =  $str ."\"message\": \"" . $msg . "\"" ;
	$str =  $str . "\n";
	$str =  $str ."}";
	echo $str;
}
//返回数组json给web
function ReturnJSONFromArray($array, $msg="", $error="", $success = "true")
{
	if($success == true) $success = "true";
	if($success == false) $success = "false";

	$str = "{\n";
	$str =  $str ."\"dataset\":\n[";

	$str =  $str . "\n\t";
	$str =  $str . json_encode2($array);

	$str =  $str ."\n],\n";
	$str =  $str ."\"success\":" . $success ."," ;
	$str =  $str . "\n";
	$str =  $str ."\"error\": \"" . ProveJSONStr($error) . "\"," ;
	$str =  $str . "\n";
	$str =  $str ."\"message\": \"" . $msg . "\"" ;
	$str =  $str . "\n";
	$str =  $str ."}";
	echo $str;
}
function ReturnJSONMsg($msg, $error="", $success = "true")
{
	if($success == true) $success = "true";
	if($success == false) $success = "false";

	$str = "{\n";
	$str =  $str ."\"dataset\":\n[],\n";
	$str =  $str ."\"success\":" . $success ."," ;
	$str =  $str . "\n";
	$str =  $str ."\"error\": \"" . ProveJSONStr($error) . "\"," ;
	$str =  $str . "\n";
	$str =  $str ."\"message\": \"" . $msg . "\"" ;
	$str =  $str . "\n";
	$str =  $str ."}";
	echo $str;
}
function ReturnJSONErrorMsg($error)
{
	ReturnJSONMsg("错误信息:", $error, false);
}
//重定向
function ReturnJSONRedirect()
{
    $error="请重新登陆";
    $success = "false";

    $js= "window.top.document.location.href='../log/login.html'";

	$str = "{\n";
	$str =  $str ."\"dataset\":\n[],\n";
	$str =  $str ."\"success\":" . $success ."," ;
	$str =  $str . "\n";
	$str =  $str ."\"error\": \"" . ProveJSONStr($error) . "\"," ;
	$str =  $str . "\n";
	$str =  $str ."\"message\": \"\"," ;
	$str =  $str . "\n";
	$str =  $str ."\"js\": \"" . ProveJSONStr($js) . "\"" ;
	$str =  $str . "\n";
	$str =  $str ."}";
	echo $str;
}

//返回给web
function ReturnHTML($array)
{
	$str = "<html>\n";
	$str = $str . "<head><title></title>";
	$str = $str . "<link type='text/css' href='./html/cs/default.css' rel='stylesheet'></link>";
	$str = $str . "</head>\n<body>\n";
	$str = $str . "  <table>\n";

	foreach($array as $val)
	{
		$str = sprintf("%s<tr><td>%s<td/></tr>\n", $str, $val);
	}

	$str = $str . "<tr><td><a href='javascript:history.go(-1)'>后退</a><td/></tr>\n";

	$str = $str . "  </table>\n";
	$str = $str . "</body>\n";

	echo $str;
}
//把多个参数（个数不定）返回给web
function PrintMsgToHTML()
{
	$array = func_get_args();
	ReturnHTML($array);
}
//替换json中的某些字符
function ProveJSONStr($str)
{
	$search  = array('\\', '"', '\'', '`');
	$replace = array('\\\\', '\"', '\\\'', '\\\'');

	return str_replace($search, $replace, $str);
}


//---------------------------------------------------
//编码成字符串
function json_encode2($obj){
	$json = new Services_JSON();
	return $json->encode($obj);
}
//解码成对象
function json_decode2($str){
	$json = new Services_JSON();
	return $json->decode($str);
}

//返回百分比格式
function GetPercentFormat($val)
{
	return (round($val, 4) * 100) . " %" ;   //格式如 12.23 %
}

//返回小数点两位
function GetFloatFormat($val)
{
	return round($val, 2);
}

function GetCurrentDateTime()
{
	return date("Y-m-d");
}

//判断两个日期大小, 大:返回1， 小返回-1, 0表示相等
function JudgeDateTime($date1, $date2)
{	  
	$tmpDate1 = date("Y-m-d", strtotime($date1));
	$tmpDate2 = date("Y-m-d", strtotime($date2));
	
	if($tmpDate1 > $tmpDate2)
		return 1;
	else if ($tmpDate1 == $tmpDate2)
		return 0;
	else
		return -1;
}

//给日期增加 $count 天
function AddDay($datetime, $count)
{
	return date("Y-m-d", strtotime("$datetime +$count day")); //日期天数相加函数
}

//根据开始日期， 结束日期， 返回日期数组
function GetDataArrayFromBeginToEnd($datetime_begin, $datetime_end)
{
	//--获取日期成数组
	$tmpDate = $datetime_begin;

	$tmpDatetimeArray = array();
	$tmpDatetimeArray[] = $tmpDate;

	while(true)
	{
		$tmpDate = AddDay($tmpDate, 1);
		$tmpJudge = JudgeDateTime($tmpDate, $datetime_end);
		if($tmpJudge == 1) 
			break; 
			
		$tmpDatetimeArray[] = $tmpDate;
	}
	return $tmpDatetimeArray;
}

//根据开始日期， 多少天， 返回日期数组
function GetDataArrayFromBeginToCount($datetime_begin, $count)
{
	//--获取日期成数组
	$tmpDate = $datetime_begin;

	$tmpDatetimeArray = array();
	$tmpDatetimeArray[] = $tmpDate;
	$i = 0;
	while(true)
	{
		$i++;
		if($i >= $count) 
			break; 
			
		$tmpDate = AddDay($tmpDate, 1);
		$tmpDatetimeArray[] = $tmpDate;
	}
	return $tmpDatetimeArray;
}


//往逻辑服务器发送消息
function socketDataToLS($server, $port, $data)
{	
	$commonProtocol = getprotobyname('TCP');
	$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
	socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>1, "usec"=>0));
	socket_connect($socket, $server, $port);
		
	if($data)
	{			
		$dataLen = strlen($data);
		$tmpData = pack('I', $dataLen) . $data;			//长度(二进制) + 内容
		
		$len = strlen($tmpData);
		$sendLen = socket_write($socket, $tmpData, $len);  //发送数据	
	}
	
	$out = @socket_read($socket, 4);
	if($out)
	{			
		$out2 = unpack("I", $out);	
		$recvLen = $out2[1];	
		
		$out = @socket_read($socket, $recvLen);
		
		//$rs = split(' ',$out);
		//$method = $rs[0];			
		//unset($rs[0]);			
		//$arr = json_decode(implode(' ',$rs),true);			
	}
	socket_close($socket);
	return trim($out);
}

//发送并接受回应包
function socketDataExt($data)
{
	$server = GetConfInfo("server"); //'192.168.1.129';
	$port   = GetConfInfo("port"); //'9999';
	$out = socketDataToLS($server, $port, $data);
	return decodeSocketDataFromLS($out);
}

function decodeSocketDataFromLS($out)
{
	$firstSpace = strpos($out, " ");
	$strCmd = substr($out, 0, $firstSpace);				//命令字
	$strContent = substr($out, $firstSpace + 1);		//内容
	$strContentArray = json_decode($strContent, true); 	//转换成数组
	//print_r($strContentArray);
	
	$resArray = array();
	$resArray["cmd"] = $strCmd;
	$resArray["content"] = $strContentArray;
	return $resArray;
}

//写记录到文本
function WriteLog($msg)
{
	$tmpDate1 = date("Y-m-d H:i:s");					//当前时间
	$tmpMsg = "[" . $tmpDate1 . "]: " . $msg . "\n";	//记录内容
	
	$logPath = GetConfInfo("log_path");					//获取记录文件所在路径
	CreateFolder($logPath);								//不存在路径, 则建立
	$logFullPath = $logPath . "log.txt";				//记录文件全路径
	
	file_put_contents($logFullPath, $tmpMsg, FILE_APPEND);  //把内容写文本
}

?>